package com.qingcloud.adminbackend.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.ImmutableMap;
import com.qingcloud.adminbackend.entity.domain.DomainTreeVO;
import com.qingcloud.adminbackend.entity.domain.SysDomain;
import com.qingcloud.adminbackend.mapper.SysDomainMapper;
import com.qingcloud.adminbackend.service.ISysDomainService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 省市区对象 服务实现类
 * </p>
 *
 * @author wangjinnan
 * @since 2018-11-16
 */
@Service
public class SysDomainServiceImpl extends ServiceImpl<SysDomainMapper, SysDomain> implements ISysDomainService {
    @Resource
    private SysDomainMapper sysDomainMapper;
    /**
     * 查询所有省
     *
     * @return
     */
    @Override
    public List<SysDomain> getAllProvince() {
        return baseMapper.selectByMap(ImmutableMap.of("city_type", "1"));
    }

    /**
     * 根据id 查询树结构
     * id 没有规则，所以树结构从下级找到上级
     * @param domainIds
     * @return
     */
    @Override
    public List<DomainTreeVO> selectTreeByIds(List<Long> domainIds) {
        List<SysDomain> domainList = null;
        QueryWrapper<SysDomain> wrapper = new QueryWrapper<>();
        if (!CollectionUtils.isEmpty(domainIds)){
            wrapper.in("id",domainIds);
        }
        wrapper.orderByDesc("city_type");
        domainList = sysDomainMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(domainList)){
            return null;
        }
        Map<Long, DomainTreeVO> domainMap = new LinkedHashMap<>();
        domainList.forEach(domain -> {
            if (domain.getCityType() != null){
                DomainTreeVO vo = new DomainTreeVO();
                vo.setId(domain.getId());
                vo.setParentId(domain.getParentId());
                vo.setCityType(Integer.valueOf(domain.getCityType()));
                vo.setDomainName(domain.getDomainName());
                vo.setLatB(domain.getLatB() != null ? domain.getLatB().toString() : "");
                vo.setLngB(domain.getLngB() != null ? domain.getLngB().toString() : "");
                vo.setLatReal(domain.getLatReal() != null ? domain.getLatReal().toString() : "");
                vo.setLngReal(domain.getLngReal() != null ? domain.getLngReal().toString() : "");
                domainMap.put(domain.getId(),vo);
            }
        });
        //整理数据 关联父子关系
        selectParent(domainMap);

        //循环递归查找 未知的上级
        recursionParent(domainMap);
        List<DomainTreeVO> voList = new ArrayList<>();
        for (Map.Entry<Long,DomainTreeVO> voEntry : domainMap.entrySet()){
            voList.add(voEntry.getValue());
        }
        return voList;
    }

    /**
     * 递归查询上级
     */
    private void recursionParent(Map<Long, DomainTreeVO> domainMap){
        List<Long> parentIds = new ArrayList<>();
        for (Map.Entry<Long,DomainTreeVO> entry : domainMap.entrySet()){
            DomainTreeVO domain = entry.getValue();
            if (domain.getParentId() != null){
                parentIds.add(domain.getParentId());
            }
        }
        if (!CollectionUtils.isEmpty(parentIds)){
            List<SysDomain> parentDomain = sysDomainMapper.selectBatchIds(parentIds);
            if (!CollectionUtils.isEmpty(parentDomain)){
                parentDomain.forEach(parent -> {
                    if (parent.getCityType() != null){
                        DomainTreeVO vo = new DomainTreeVO();
                        vo.setId(parent.getId());
                        vo.setParentId(parent.getParentId());
                        vo.setCityType(Integer.valueOf(parent.getCityType()));
                        vo.setDomainName(parent.getDomainName());
                        vo.setLatB(parent.getLatB() != null ? parent.getLatB().toString() : "");
                        vo.setLngB(parent.getLngB() != null ? parent.getLngB().toString() : "");
                        vo.setLatReal(parent.getLatReal() != null ? parent.getLatReal().toString() : "");
                        vo.setLngReal(parent.getLngReal() != null ? parent.getLngReal().toString() : "");
                        domainMap.put(parent.getId(),vo);
                    }
                });
                selectParent(domainMap);
                recursionParent(domainMap);
            }
        }
    }

    /**
     * 查找上级
     */
    private void selectParent(Map<Long, DomainTreeVO> domainMap){
        Iterator<Map.Entry<Long, DomainTreeVO>> iterator = domainMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<Long, DomainTreeVO> next = iterator.next();
            DomainTreeVO domain = next.getValue();
            if (domain.getId().intValue() == 131000){
                System.out.println(JSONObject.toJSONString(domain));
            }
            if (domain.getParentId() != null){
                DomainTreeVO parent = domainMap.get(domain.getParentId());
                if (parent != null){
                    if (parent.getChild() == null){
                        parent.setChild(new ArrayList<>());
                    }
                    parent.getChild().add(domain);
                    iterator.remove();
                }
            }
        }
    }
}
